<template>
    <div class="app-container">
        <!-- <span>{{userTaskData}}</span> -->
        <div style="font-size: 14px;color: #606266;    line-height: 36px">
            <el-form ref="userTaskData" :v-model="userTaskData">
                <el-row>
                    <el-col span="3.5" style="padding-right: 20px;">
                        <el-form-item label="考核任务：">
                            <el-input v-model="userTaskData.tetaName" :disabled="true"/>
                        </el-form-item>
                    </el-col>
                    <el-col span="3.5">
                        <el-form-item label="受评人：">
                            <el-input v-model="userTaskData.tetaCoverUsername" :disabled="true"/>
                        </el-form-item>
                    </el-col>
                </el-row>                      
            </el-form>
            
            <!-- <el-divider></el-divider> -->
            
            <el-form ref="userTaskItemData" :model="userTaskData" :rules="socreDataRules">
                <el-form-item prop="userTaskData.itemDatelist">
                    <el-table  ref="itemDatelist" :data="userTaskData.itemDatelist" style="width: 100%;margin-bottom: 20px;" row-key="customIndex" :span-method="arraySpanMethod"
                    border  default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                    <el-table-column prop="teitContent" label="考评项描述">
                    </el-table-column>
                    <!-- <el-table-column label="评分" align="center">
                        <template slot-scope="scope" >
                            <span v-if="scope.row.children == null || scope.row.children.length == 0 ">
                                <span v-if="!tableIsEdit" v-show="!tableIsEdit">{{scope.row.tedaPoint}}</span>
                                {{'itemDatelist.' + scope.$index + '.tedaPoint'}}
                                <el-form-item v-if="tableIsEdit && scope.row.hasOwnProperty('children') " :prop=" 'itemDatelist.' + scope.$index + '.tedaPoint' " label=" " style="margin-bottom:0px;z-index: 999;" :rules="socreDataRules.tedaPoint">
                                    <el-input v-show="tableIsEdit" size="mini" v-model="scope.row.teitId" :placeholder="'请输入0~' + scope.row.tesiPercent  + '的分值'" />
                                </el-form-item>
                            </span>
                        </template>
                    </el-table-column>-->
                    <el-table-column label="评分" align="center" prop="tedaPoint">
                        <template v-slot="{ $index, row }" >
                            <span v-if="row.children == null || row.children.length == 0 ">
                                <span v-if="!tableIsEdit">{{row.tedaPoint}}</span>
                                <span style="color:red; float: left;margin-top: 10px;">*</span>
                                <el-form-item  v-if="tableIsEdit " style="margin-bottom: 22px;margin-left: 15px;"  :prop=" `${`itemDatelist.${row.path}.tedaPoint`}`"
                                    label=""  :rules="socreDataRules.tedaPoint">
                                    <el-input size="mini" v-model="row.tedaPoint"  :placeholder="'请输入1~' + row.tesiPercent  + '的分值'" />
                                </el-form-item>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="tedaComment" label="评价描述" align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.children == null || scope.row.children.size == 0 ">
                                <span v-if="!tableIsEdit">{{scope.row.tedaComment}}</span>
                                <el-form-item v-if="tableIsEdit" style="margin-bottom: 22px;">
                                    <el-input size="mini" label="请输入评价内容" v-model="scope.row.tedaComment"></el-input>
                                </el-form-item>
                            </span>
                        </template>
                    </el-table-column>
                </el-table>
                </el-form-item>
                <el-input type="hidden" :v-model="userTaskData.tetaId"></el-input>
            </el-form>
            <div style="text-align:center">
                <span v-show="tableIsEdit">
                    <el-button   type="primary" @click="submit(0)">保存</el-button>
                    <el-button   type="primary" @click="submit(1)">提交</el-button>
                </span>
            </div>
        </div>
    </div>
</template>
<script>
import{infoByUserTask, saveOrSubmitData} from  "@/api/teacher/evaluation/userTask"
export default {
    data() {
        var validTaskScoreItem = (rule, value, callback) => {
            // console.log("userTaskItemData", rule, "value=>",value);
            if (value == '' || value == undefined ) {
                callback(new Error("请输入打分数据"));
            } else {
                if (isNaN(value)) {
                    callback(new Error("打分数据请输入数字"));
                } else {    
                    var valueNumber = Number(value);
                    var checkPercent = this.getSocreTesiPercent(rule.field);
                    if (!(valueNumber >= 1 && valueNumber <= checkPercent)) {
                        // console.log("请输入1~" + checkPercent + "的打分数据");
                        callback(new Error("请输入1~" + checkPercent + "的打分数据"));
                    } else {
                        // console.log("正常", rule.field);
                        this.$refs.userTaskItemData.clearValidate(rule.field);
                        callback();
                    }
                }
            }
        };
        return {
            teutId: undefined,
            userTaskData : {
                tetaName: "",
                tetaCoverUsername: "",
                itemDatelist: []
            },
            tableIsEdit: false,
            socreDataRules: {
                tedaPoint: [
                     {require: true, validator: validTaskScoreItem,  trigger: "blur" }
                    //{require: true, message: "请输入评分",  trigger: "blur" }
                ]
            }
        }
    },
    created() {
        this.teutId = this.$route.query.teutId;
        console.log("this.teutId", this.teutId);
        this.getUserTaskInfo();
    },
    methods: {
        getUserTaskInfo() {
            infoByUserTask(this.teutId).then(response => {
                // console.log(response);
                this.userTaskData = response.data
                // console.log("this.tableIsEdit", this.tableIsEdit, this.userTaskData.teutStatus);
                if (this.userTaskData.teutStatus==3 || this.userTaskData.teutStatus==4) {
                    this.tableIsEdit = false;
                } else {
                    this.tableIsEdit = true;
                }
                this.setIndex(this.userTaskData.itemDatelist)
                // console.log("this.tableIsEdit", this.tableIsEdit, this.userTaskData.teutStatus);
            });
        },
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (row.children!=null && row.children.length != 0) {
                if (columnIndex === 0) {
                    return [1, 3];
                } else {
                    return [0, 0];
                }
            }
        },
        submit(oper) {
            console.log("oper", oper);
          
            this.$refs.userTaskItemData.validate(valid => {
                if (valid) {
                    console.log("验证通过")
                    if (oper == 0) {
                        ;
                    } else if ( oper == 1) {
                        this.userTaskData.teutStatus = 4;
                    } else {
                        return;
                    }
                    saveOrSubmitData(this.userTaskData).then(response => {
                        if (response.code === 200) {
                            this.userTaskData = response.data;
                            if (this.userTaskData.teutStatus == 3 || this.userTaskData.teutStatus == 4) {
                                this.msgSuccess("提交成功");
                                this.tableIsEdit = false;
                            } else {
                                this.msgSuccess("保存成功");
                            }
                            this.getUserTaskInfo();
                        } else {
                            this.msgError(response.message);
                        }
                    });
                }
            });
           
        },
        setIndex(data) {
            let queue = [...data];
            let loop = 0;
            this.num = 0;
            this.expendArrs = [];
            this.listLen = 0;
            while (queue.length > 0) {
                loop++;
                [...queue].forEach((child, i) => {
                queue.shift();
                this.num++;
                if (loop == 1) {
                    child.customIndex = i + 1 + "";
                    child.currentIndex = i;
                    child.path = i;
                    child.pid = "";
                }
                if (child.children && child.children.length > 0) {
                    child.dataType = 1;
                    for (let ci = 0; ci < child.children.length; ci++) {
                    child.children[ci].currentIndex = ci;
                    child.children[ci].customIndex =
                        child.customIndex + "." + (ci + 1);
                    child.children[ci].path = child.path + ".children." + ci;
                    child.children[ci].pid = child.customIndex;
                    }
                    queue.push(...child.children);
                } else {
                    child.dataType = 2;
                }
                child.expended = child.expended || "true";
                if (child.expended === "true") {
                    this.expendArrs.push(child.customIndex);
                }
                });
                //console.log("this.expendArrs", this.expendArrs);
            }
        },
        getPathByKey(value, key, arr) {
            let temppath = [];
            let realPath = "";
            try {
                function getNodePath(node) {
                temppath.push(node.currentIndex);
                //找到符合条件的节点，通过throw终止掉递归
                if (node[key] === value) {
                    temppath.forEach((v, i) => {
                    if (i == 0) {
                        realPath += "." + v;
                    } else {
                        realPath += `.children.${v}`;
                    }
                    });
                    // temppath = temppath.join(",")
                    throw "GOT IT!";
                    // return;
                }
                if (node.children && node.children.length > 0) {
                    for (var i = 0; i < node.children.length; i++) {
                    getNodePath(node.children[i]);
                    }

                    //当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
                    temppath.pop();
                } else {
                    //找到叶子节点时，删除路径当中的该叶子节点
                    temppath.pop();
                }
            }

                for (let i = 0; i < arr.length; i++) {
                    getNodePath(arr[i]);
                }
            } catch (e) {
                return realPath;
            }
        },
        getSocreTesiPercent(valueIndex) {
            // "itemDatelist.0.children.0.tedaPoint"
            var getValueResult = undefined;
            var childrenIndex = valueIndex.indexOf("children");
            var levelOneFlag = undefined;
            var levelTwoFlag = undefined;
            if (childrenIndex > 0) {
                levelOneFlag = valueIndex.substring(13, childrenIndex - 1);
                levelTwoFlag = valueIndex.substring(childrenIndex + 9, valueIndex.indexOf("tedaPoint") - 1);
                //valueIndex.sumb
            } else {
                levelOneFlag = valueIndex.substring(13, valueIndex.indexOf("tedaPoint") - 1);
            }

            //console.log("levelOneFlag", levelOneFlag, "levelTwoFlag", levelTwoFlag);
            
            if(levelTwoFlag != undefined) {
                getValueResult = this.userTaskData.itemDatelist[levelOneFlag].children[levelTwoFlag].tesiPercent;
            } else {
                getValueResult = this.userTaskData.itemDatelist[levelOneFlag].tesiPercent;
            }
            
            //console.log("getValueResult", getValueResult);
            return getValueResult;
        }
        
    }
}
</script>